package com.itheima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.dto.ArticleHomeDto;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.mapper.ApArticleConfigMapper;
import com.itheima.article.mapper.ApArticleContentMapper;
import com.itheima.article.mapper.ApCollectionMapper;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.vo.ArticleInfo;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.pojo.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>已发布的文章信息 业务实现</p>
 * @package com.itheima.article.service.impl
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private WmNewsFeign wmNewsFeign;

    /**
     * 同步自媒体文章到文章微服
     *
     * @param dto
     */
    @Override
    @Transactional
    public void saveArticleInfo(ArticleInfoDto dto) {
        //同步发布文章信息article
        log.info("同步文章表信息开始");
        //根据是否有文章id判断是否是旧文章
        ApArticle apArticle = dto.getApArticle();
        Long apArticleId = apArticle.getId();
        if (null != apArticleId) {
            //是旧文章重新审核发布
            //删除旧文章,内容、config
            removeById(apArticleId);
            Map<String, Object> apArticleIdMap = new HashMap<>();
            apArticleIdMap.put("apArticleId", apArticleId);
            contentMapper.deleteByMap(apArticleIdMap);
            configMapper.deleteByMap(apArticleIdMap);
            apArticle.setId(null);
        }
        save(apArticle);
        log.info("同步文章表信息成功");
//        获取新的文章id  底层在添加完后会返回插入数据的主键值
        apArticleId = apArticle.getId();
        //同步文章内容
        log.info("同步文章内容表开始");
        ApArticleContent apArticleContent = dto.getApArticleContent();
        apArticleContent.setArticleId(apArticleId);
        contentMapper.insert(apArticleContent);
        log.info("同步文章内容表成功");
        //同步文章config
        log.info("同步文章配置表开始");
        ApArticleConfig apArticleConfig = dto.getApArticleConfig();
        apArticleConfig.setArticleId(apArticleId);
        configMapper.insert(apArticleConfig);
        log.info("同步文章配置表成功");
        //更新自媒体文章的article_id、状态
        WmNews wmNews = new WmNews();
        //根据id更新
        wmNews.setId(dto.getWmNewsId());
        //状态已发布
        wmNews.setStatus(BusinessConstants.WmNewsConstants.STATUS_PUBLISHED);
        //修改上架状态为已上架即为1
        wmNews.setEnable(BusinessConstants.WmNewsConstants.ENABLE_ON);
        //修改文章id
        wmNews.setArticleId(apArticleId);
        ResultVo<WmNews> updateResultVo = wmNewsFeign.update(wmNews);
        if (!updateResultVo.isSuccess()) {
            //文章更新失败
            throw new LeadNewsException("远程调用更新自媒体状态失败");
        }
        log.info("远程调用更新自媒体状态成功");
    }

    /**
     * app端分页展示
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo<ApArticle> findPage(ArticleHomeDto dto, int loadType) {
        //参数校验
        dto.checkSize();
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        //分页
        IPage<ApArticle> pageInfo = new Page<>(dto.getLoaddir(), dto.getSize());
        //构建查询条件
        List<ApArticle> list = getBaseMapper().findPage(pageInfo, dto, loadType);

        return PageResultVo.pageResult(pageInfo.getCurrent(), pageInfo.getSize(), pageInfo.getTotal(), list);
    }

    /**
     * 查看article文章详情
     *
     * @param paramMap
     * @return
     */
    @Override
    public ArticleInfo loadArticleInfo(Map<String, String> paramMap) {
        Long articleId = Long.valueOf(paramMap.get("articleId"));
        //根据articleId查询文章内容
        LambdaQueryWrapper<ApArticleContent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = contentMapper.selectOne(lqw);
        //根据articleId查询文章配置信息
        LambdaQueryWrapper<ApArticleConfig> queryWrapper = Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, articleId)
                .eq(ApArticleConfig::getIsDelete, 0)
                .eq(ApArticleConfig::getIsDown, 0);
        ApArticleConfig articleConfig = configMapper.selectOne(queryWrapper);
        if (null == articleConfig) {
            throw new LeadNewsException("文章已下架或已删除!");
        }
        //封装ArticleInfo
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setApArticleContent(apArticleContent);
        articleInfo.setApArticleConfig(articleConfig);
        return articleInfo;
    }


}
